import { CheckSquareOutlined } from '@ant-design/icons'
import { connect } from 'dva'

import { deleteNursingItemApi, enableNursingItemApi, nursingTypeListApi } from '@/api/pcs/pcsNursingItem'
import AekButton from '@/components/AekButton'
import AekLinkButton from '@/components/AekLinkButton'
import AekTable from '@/components/AekTable'
import PageLayout from '@/components/PageLayout'
import SearchForm from '@/components/SearchForm'
import { namespace } from '@/models/pcs/pcsNursingItem'
import { getPagination, message, modal } from '@/utils/antdHelper'
import { getBasicFn } from '@/utils/dvaUtil/index'
import {
  PCS_ATTRIBUTE_TYPE_ENUM,
  PCS_DEFAULT_CHECKED_IN_NURSING_PLAN_ENUM,
  PCS_DISPLAY_IN_LIFELOG_ENUM,
  PCS_NURSING_ITEM_STATUS_ENUM,
} from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import EditModal from './components/EditModal'

/** 陪护 - 护嘱事项管理 */
const Index = ({ modelState, loading }) => {
  const { pageList, pagination, searchParams } = modelState
  const { toAction, getLoading } = getBasicFn({ namespace, loading })

  const add = async () => {
    await EditModal.PromiseThen()
    message.success('新增成功')
    toAction('getPageList')
  }

  const edit = async row => {
    await EditModal.PromiseThen({
      row,
    })
    message.success('修改成功')
    toAction('getPageList')
  }

  const remove = async ({ id, nursingItemName }) => {
    modal.confirm({
      title: '删除',
      content: `确认删除护嘱事项【${nursingItemName}】？`,
      onOk: async () => {
        await requestWithTry(deleteNursingItemApi, { id })
        message.success('删除成功')
        if ((pagination.current - 1) * pagination.pageSize === pagination.total - 1) {
          toAction('getPageList', { current: pagination.current - 1 || 1 })
        } else {
          toAction('getPageList')
        }
      },
    })
  }

  const enable = async ({ id }) => {
    await requestWithTry(enableNursingItemApi, { id, status: 1 })
    message.success('启用成功')
    toAction('getPageList')
  }

  const disable = ({ id, nursingItemName }) => {
    modal.confirm({
      title: `是否确认停用护嘱事项【${nursingItemName}】？`,
      onOk: async () => {
        await requestWithTry(enableNursingItemApi, { id, status: 0 })
        message.success('停用成功')
        toAction('getPageList')
      },
    })
  }

  /** @type {import("@/components/SearchForm").SearchFormProps} */
  const searchProps = {
    searchParams,
    formData: [
      {
        field: 'nursingItemName',
        label: '护嘱事项',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'nursingItemContent',
        label: '内容',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'nursingTypeId',
        label: '分类',
        component: {
          name: 'AekSelect',
          props: {
            api: nursingTypeListApi,
            fieldNames: {
              value: 'id',
              label: 'nursingTypeName',
            },
          },
        },
      },
      {
        field: 'displayInLifeLog',
        label: '照护日志',
        component: {
          name: 'Select',
          props: {
            options: PCS_DISPLAY_IN_LIFELOG_ENUM.options,
          },
        },
      },
      {
        field: 'status',
        label: '状态',
        component: {
          name: 'Select',
          props: {
            options: PCS_NURSING_ITEM_STATUS_ENUM.options,
          },
        },
      },
    ],
    onSearch: values => {
      toAction({ searchParams: values })
      toAction({ pagination: { current: 1 } }, true)
      toAction('getPageList')
    },
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    configKey: namespace,
    rowKey: 'id',
    loading: getLoading('getPageList'),
    dataSource: pageList,
    pagination: getPagination(pagination, (current, pageSize) => {
      toAction('getPageList', { current, pageSize })
    }),
    columns: [
      { dataIndex: 'nursingItemName', title: '护嘱事项' },
      { dataIndex: 'nursingTypeName', title: '护嘱分类' },
      { dataIndex: 'nursingItemContent', title: '内容', ellipsis: true },
      { dataIndex: 'attribute', title: '属性', width: 130, enum: PCS_ATTRIBUTE_TYPE_ENUM },
      { dataIndex: 'defaultCheckedInNursingPlan', title: '护嘱计划', enum: PCS_DEFAULT_CHECKED_IN_NURSING_PLAN_ENUM },
      {
        dataIndex: 'lifeLogWeight',
        title: '生活日志',
        width: 150,
        render: (text, { displayInLifeLog }) =>
          displayInLifeLog ? (
            <span>
              <CheckSquareOutlined className='text-green' />
              {`（权重：${text || ''}）`}
            </span>
          ) : (
            '-'
          ),
      },
      { dataIndex: 'createUserName', title: '创建人' },
      { dataIndex: 'createTime', title: '创建时间', isDateTime: true },
      {
        key: 'operate',
        title: '操作',
        fixed: 'right',
        width: 150,
        className: 'text-center!',
        render: (_, row) => (
          <>
            <AekLinkButton onClick={() => edit(row)}>编辑</AekLinkButton>
            <AekLinkButton danger onClick={() => remove(row)}>
              删除
            </AekLinkButton>
            <AekLinkButton
              danger={row.status}
              onClick={() => {
                row.status ? disable(row) : enable(row)
              }}
            >
              {row.status ? '停用' : '启用'}
            </AekLinkButton>
          </>
        ),
      },
    ],
  }

  return (
    <PageLayout
      extraSuffix={
        <AekButton type='primary' onClick={add}>
          新建
        </AekButton>
      }
    >
      <SearchForm {...searchProps} />
      <AekTable {...tableProps} />
    </PageLayout>
  )
}

export default connect(store => ({
  modelState: store[namespace],
  loading: store.loading,
}))(Index)
